<?php

/**
 * +----------------------------------------------------------------------
 * | TickyPHP [ This is a freeware ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2015 All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: 罗敏贵 <e-mail:minguiluo@163.com> <QQ:271391233>
 * +----------------------------------------------------------------------
 * | SVN: $Id: Member.php 87573 2018-09-04 09:49:32 luomingui $
 * +----------------------------------------------------------------------
 * | 文件功能：对应的表名:tky_member
 * +----------------------------------------------------------------------
 */

namespace application\admin\controller;

use ticky\request;
use ticky\response;

class member extends base {

    //首页
    public function index() {
        //获取默认密码
        $default_password = get_config('default_password');
        $search = $this->search_frm();
        if (request::get('roleid', 0) == '0') {
            $ret = db('member m')
                    ->field('m.*')
                    ->where($search['sql'])
                    ->newpage();
        } else {
            $ret = db('member m')
                    ->field('m.*')
                    ->join(db()->prefix . "auth_role_member am on m.uid=am.uid")
                    ->join(db()->prefix . "auth_role r on r.roleid=am.roleid")
                    ->where($search['sql'])
                    ->newpage();
        }
        $this->assign('page', $ret['page']);
        $this->assign('items', $ret['items']);
        $this->assign('search', $search['arr']);
        $this->assign('default_password', $default_password);

        $this->display('member/index');
    }

    // 添加记录
    public function add() {
        if (request::isPost()) {
            $data = $this->post_frm();
            $data['password'] = password(get_config('default_password'));
            $uid = db('member')->insert($data);
            //赋予角色
            $arr = array();
            $arr['uid'] = $uid;
            $arr['roleid'] = request::post('roleid', 0);
            db('auth_role_member')->insert($arr);
            showmsg('添加成功', '/admin/member');
        } else {
            $this->assign('postUrl', '/admin/member/add');
            $this->assign('action', '添加');
            $this->display('member/member_add');
        }
    }

    //修改用户详细信息
    public function update() {
        load_extend('form.class.php');
        $uid = request::get('uid', 0);
        $item = get_memberinfo($uid);
        if (request::isPost()) {
            if ($member_profile) {
                db('member_profile')->update($_POST, array('uid' => $uid));
                $msg = "修改";
            } else {
                $msg = "添加";
                $_POST['uid'] = $uid;
                db('member_profile')->insert($_POST, false, false, false);
            }
            showmsg($msg . '用户详细信息成功', '/admin/member');
        } else {

            $nowy = date('Y');
            $birthyeayhtml = '';
            for ($i = 0; $i < 100; $i++) {
                $they = $nowy - $i;
                if (empty($_GET['all']))
                    $selectstr = $they == $item['birthyear'] ? ' selected=\"selected\"' : '';
                $birthyeayhtml .= "<option value=\"$they\"$selectstr>$they</option>";
            }
            $birthmonthhtml = '';
            for ($i = 1; $i < 13; $i++) {
                if (empty($_GET['all']))
                    $selectstr = $i == $item['birthmonth'] ? ' selected=\"selected\"' : '';
                $birthmonthhtml .= "<option value=\"$i\"$selectstr>$i</option>";
            }
            $birthdayhtml = '';
            for ($i = 1; $i < 29; $i++) {
                if (empty($_GET['all']))
                    $selectstr = $i == $item['birthday'] ? ' selected=\"selected\"' : '';
                $birthdayhtml .= "<option value=\"$i\"$selectstr>$i</option>";
            }
            $this->assign('birthyeayhtml', $birthyeayhtml);
            $this->assign('birthmonthhtml', $birthmonthhtml);
            $this->assign('birthdayhtml', $birthdayhtml);

            $this->assign('postUrl', '/admin/member/edit_profile');
            $this->assign('action', '添加');
            $this->assign('item', $item);
            $this->display('member/edit_profile');
        }
    }

    // 删除记录
    public function delete() {
        $id = request::get('uid', 0);
        db('member')->delete(['uid' => $id]);
        db('auth_role_member')->delete(['uid' => $id]);
        db('tky_member_profile')->delete(['uid' => $id]);
        showmsg('删除成功', '/admin/member');
    }

    // 批量删除
    public function batchremove() {
        $optype = request::post('optype', 'del');
        $ids = request::post('ids', []);
        if ($optype == "del") {
            db('member')->delete('uid in(' . implode(",", $ids) . ')');
            db('auth_role_member')->delete('uid in(' . implode(",", $ids) . ')');
            db('tky_member_profile')->delete('uid in(' . implode(",", $ids) . ')');
            showmsg('删除成功', '/admin/member');
        } else if ($optype == 'role') {
            $roleid = request::post('roleid', '0');
            if ($roleid != '0') {
                for ($i = 0; $i <= count($ids); $i++) {
                    $tid = $ids[$i];
                    if (!is_null($tid)) {
                        $sql = "INSERT INTO `tky_auth_role_member` (`uid`, `roleid`) VALUES ('" . $tid . "', '" . $roleid . "');";
                        db('auth_role_member')->query($sql);
                    }
                }
            }
            showmsg('批量设置角色成功', '/admin/member');
        }
    }

    //查询条件
    private function search_frm() {
        $search = request::get('search', []);
        $search['roleid'] = request::get('roleid', 0);
        //debug($search);
        $where = '1=1 and m.adminid=1 ';
        if ($uid = trim($search['uid'])) {
            $where .= "and m.uid = '{$uid}' ";
        }
        if ($roleid = trim($search['roleid'])) {
            $where .= "and am.roleid = '{$roleid}' ";
        }
        if ($username = trim($search['username'])) {
            $where .= "and (m.username like '%{$username}%' or m.email like '%{$username}%') ";
        }
        if ($amount = trim($search['amount'])) {
            $where .= "and m.amount = '{$amount}' ";
        }
        if ($adminid = trim($search['adminid'])) {
            $where .= "and m.adminid = '{$adminid}' ";
        }
        if ($status = trim($search['status'])) {
            $where .= "and m.status = '{$status}' ";
        }
        if ($dateline = trim($search['dateline'])) {
            $where .= "and m.dateline = '{$dateline}' ";
        }
        return [
            'arr' => $search,
            'sql' => $where
        ];
    }

    //表单数据
    private function post_frm() {
        $arr = array();
        $arr['username'] = request::post('username', '');
        $arr['email'] = request::post('email', '');
        $arr['avatarstatus'] = request::post('avatarstatus', '0');
        $arr['amount'] = request::post('amount', '0');
        $arr['regip'] = $arr['lastloginip'] = request::getClientIp();
        $arr['regdate'] = $arr['lastlogintime'] = time();
        $arr['adminid'] = 1;
        $arr['timeoffset'] = request::post('timeoffset', '');
        $arr['status'] = 1;
        $arr['dateline'] = time();
        return $arr;
    }

    /**
     * 重置密码
     */
    public function reset_password() {
        $uid = request::get('uid', 0);
        $user = db('member')->where(['uid' => $uid])->find();
        if (!$user) {
            response::ajax(['code' => 301, 'msg' => '抱歉，该会员不存在']);
        }
        $default_password = password(get_config('default_password'));
        $result = db('member')->update(['password' => $default_password], ['uid' => $uid]);
        if ($result !== false) {
            response::ajax(['code' => 200, 'msg' => '密码重置成功!']);
        } else {
            response::ajax(['code' => 500, 'msg' => '密码重置失败!']);
        }
    }

    //修改密码
    public function change_password() {
        if (request::isPost()) {
            $uid = request::post('uid', '0');
            $oldpass = request::post('oldpass', '');
            $password = request::post('password', '');
            captcha::instance()->check_code();

            if (!db('member')->where(array('uid' => $uid, 'password' => password($oldpass)))->find()) {
                showmsg('原密码错误!');
            }
            if (!is_password($password)) {
                showmsg('新密码不符合规范!');
            }
            if (db('member')->update(array('password' => password($password)), array('uid' => $uid))) {
                showmsg(L('operation_success'), '', 1);
            } else {
                showmsg(L('operation_failure'));
            }
        } else {
            $this->display('member/change_password');
        }
    }

}
